package cn.bat.slsystem.control;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;







import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.bat.slsystem.pojo.AuFunction;
import cn.bat.slsystem.pojo.AuUser;
import cn.bat.slsystem.pojo.QuanXianList;
import cn.bat.slsystem.service.AuFunctionServicce;
import cn.bat.slsystem.service.UserService;
import cn.bat.slsystem.tools.Constants;

@Controller
@RequestMapping(value="/user")
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private AuFunctionServicce auFunctionServicce;

	@RequestMapping(value="/test.html")
	public void test(String[] ss){
		for (String string : ss) {
			System.out.println(string);
		}

	}

	@RequestMapping(value="/login.html")
	public String login(){
		return "login";
	}

	@RequestMapping(value="/dologin.html")
	@ResponseBody
	public Object dologin(String longinCode,String password,String code,HttpSession session){
		System.out.println("======================登录");
		System.out.println("============验证码"+code);
		String check=(String)session.getAttribute("yzm");
		System.out.println(session.getAttribute("yzm"));
		AuUser auUser= userService.login(longinCode, password);
		String msg=null;
		if(code.equals(check)){
			if(auUser!=null){
				if(auUser.getIsstart()==1){
					int roleid=Integer.valueOf(auUser.getRoleid().toString());
					List<AuFunction> list2=auFunctionServicce.paths(roleid);
					List<String> list3 =new ArrayList<String>();
					for (AuFunction auFunction : list2) {
						if(null != auFunction.getFuncurl()){
							list3.add(auFunction.getFuncurl());
						}
					}
					List<AuFunction> list=auFunctionServicce.serch(roleid);
					List<QuanXianList> newlist=new ArrayList<QuanXianList>();
					for (AuFunction auFunction : list) {
						int parentid=Integer.parseInt(auFunction.getId().toString());
						List<AuFunction> list1=auFunctionServicce.serchbyrole(roleid, parentid);
						String name=auFunction.getFunctionname();
						QuanXianList qxl=new QuanXianList(name,list1);
						newlist.add(qxl);
					}
					session.setAttribute(Constants.lanjie,list3);
					session.setAttribute(Constants.quanxian, newlist);
					session.setAttribute(Constants.USER_SESSION, auUser);
					System.out.println("===================权限"+auUser.getIsstart());
					msg="ok";
				}else{
					msg="forbidden";
				}
			}else{
				msg="no";
			} 
		}else{
			msg="check";
		}
		return msg;
	}

	@RequestMapping(value="/mainpage.html")
	public String mainpage(){
		return "mainpage";
	}

	@RequestMapping(value="/updatepwd.html")
	public String updatepwd(){
		return "updatepwd";

	}

	@RequestMapping(value="/doupdatepwd.html")
	public String updatepwd(String password,HttpSession session){
		AuUser auUser =(AuUser) session.getAttribute(Constants.USER_SESSION);
		String loginCode=auUser.getLogincode();
		int count = userService.updateByCode(loginCode, password);
		return "login";

	}

	@RequestMapping(value="/add.html")
	public String add(){
		return "useradd";
	}

	@RequestMapping(value="/doadd.html")
	public String doadd(AuUser auUser,MultipartFile partFile1,MultipartFile partFile2,HttpSession session){
		String n1=partFile1.getOriginalFilename();
		String na1=n1.substring(n1.indexOf("."));
		String n2=partFile2.getOriginalFilename();
		String na2=n2.substring(n2.indexOf("."));
		String name1=UUID.randomUUID().toString()+na1;
		String path1=session.getServletContext().getRealPath("upload/");
		File file1=new File(path1,name1);


		String name2=UUID.randomUUID().toString()+na2;
		String path2=session.getServletContext().getRealPath("upload/");
		File file2=new File(path2,name2);

		try {
			partFile1.transferTo(file1);
			partFile2.transferTo(file2);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		AuUser auUser2=(AuUser) session.getAttribute(Constants.USER_SESSION);
		auUser.setIdcardpicpath("/upload/"+name1);
		auUser.setBankpicpath("/upload/"+name2);
		auUser.setCreatetime(new Date());
		auUser.setIsstart(1);
		auUser.setRetercode(auUser2.getUsername());
		userService.insert(auUser);
		return "redirect:/user/userlist.html";

	}

	@RequestMapping(value="/userlist.html")
	public String list(HttpSession session){
		List<String> list = (List) session.getAttribute(Constants.lanjie);
		for (String path : list) {
			if(path.equals("user/userlist.html")){
				return "userlist";
			}
		}
		
		return "login";
	}

	@RequestMapping(value="/listAll.html")
	@ResponseBody
	public Object listAll(String name,@RequestParam(defaultValue="1",required=false)
	Integer pageIndex,HttpSession session){
		PageHelper.startPage(pageIndex,5);
		List list=userService.listAll(name);
		PageInfo<AuUser> page=new PageInfo<AuUser>(list);
		session.setAttribute("page", page);
		return page;
	}


	@RequestMapping(value="/updateById.html")
	public String update(AuUser auUser,MultipartFile partFile1,MultipartFile partFile2,HttpSession session){
		String n1=partFile1.getOriginalFilename();
		String na1=n1.substring(n1.indexOf("."));
		String n2=partFile2.getOriginalFilename();
		String na2=n2.substring(n2.indexOf("."));
		String name1=UUID.randomUUID().toString()+na1;
		String path1=session.getServletContext().getRealPath("upload/");
		File file1=new File(path1,name1);
		String name2=UUID.randomUUID().toString()+na2;
		String path2=session.getServletContext().getRealPath("upload/");
		File file2=new File(path2,name2);

		try {
			partFile1.transferTo(file1);
			partFile2.transferTo(file2);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		AuUser auUser2=(AuUser) session.getAttribute(Constants.USER_SESSION);
		auUser.setIdcardpicpath("/upload/"+name1);
		auUser.setBankpicpath("/upload/"+name2);
		auUser.setLastupdatetiame(new Date());
		userService.updateById(auUser);
		return "redirect:/user/userlist.html";

	}

	@RequestMapping(value="/updateAuthority.html")
	@ResponseBody
	public Object updateAuthority(int id,int start){
		return userService.updateAuthority(id, start);
	};

	@RequestMapping(value="/logout.html")
	public String logout(HttpSession session){
		session.invalidate();
		return "login";
	}

	@RequestMapping(value="/serchbyid.html")
	public String serchbyid(@RequestParam(value="id") int id,HttpSession session){
		AuUser auUser=userService.serchById(id);
		System.out.println(id);
		System.out.println(auUser);
		session.setAttribute("updateAuUser", auUser);
		return "userupdate";
	}

	@RequestMapping(value="/del.html")
	public String del(int id){
		if(userService.delById(id)==1){
			return "redirect:/user/userlist.html";
		}
		return "no";
	}

	@RequestMapping(value="/serchByName.html")
	@ResponseBody
	public Object serchbyname(String name){
		if(userService.serchByName(name)!=null){
			return 0;
		}
		return 1;
	}

	@RequestMapping(value="/checked.html")
	@ResponseBody
	public Object checked(String oldpasswoed,HttpSession session){
		AuUser auUser =(AuUser) session.getAttribute(Constants.USER_SESSION);
		String check=null;
		if(auUser.getPassword().equals(oldpasswoed)){
			check="ok";
		}else{
			check="no";
		}
		return check;
	}
	@RequestMapping(value="/newuserlist.html")
	public String list1(){
		return "newuserlist";
	}
	@RequestMapping(value="/serchReter.html")
	@ResponseBody
	public Object serchbyreter(HttpSession session){
		System.out.println("+++++++++++++++++"+session.getAttribute(Constants.USER_SESSION));
		AuUser auUser =(AuUser) session.getAttribute(Constants.USER_SESSION);
		List<AuUser> list=userService.serchByReter(auUser.getLogincode());
		return list;
	}

	@RequestMapping(value="/download.html")
	@ResponseBody
	public Object download(String path,HttpSession session,HttpServletResponse response){
		String uploadpath=session.getServletContext().getRealPath("upload");
		String destinationfileName=path.substring(8);
		String newpath=uploadpath+"\\"+destinationfileName;
		System.out.println(newpath);
		InputStream fis;

		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");

		File file = new File(newpath);
		try {

			if (!file.exists()) {

				System.out.println("=========失败");
			} else {
				// 设置相应头，控制浏览器下载该文件，这里就是会出现当你点击下载后，出现的下载地址框
				response.setHeader("Content-Disposition",
						"attachment;filename=" + path);
				// 读取要下载的文件，保存到文件输入流
				FileInputStream in = new FileInputStream(uploadpath + "\\" + destinationfileName);
				// 创建输出流
				OutputStream out = response.getOutputStream();
				// 创建缓冲区
				byte buffer[] = new byte[1024];
				int len = 0;
				// 循环将输入流中的内容读取到缓冲区中
				while ((len = in.read(buffer)) > 0) {
					// 输出缓冲区内容到浏览器，实现文件下载
					out.write(buffer, 0, len);
				}
				// 关闭文件流
				in.close();
				// 关闭输出流
				out.close();
				return null;
			}
		} catch (Exception e) {
			// TODO: handle exception

		}

		return "ok";
	}
}
